import React, { useState } from 'react'
import type { FC, Key } from 'react'
import { Button, Flex, ConfigProvider, Modal, Spin } from 'antd'
import {
  PlusOutlined,
  DeleteOutlined,
  FileExcelOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons'
import { batchRemoveUserApi, getUidsToUsersApi } from '@/services/userApi'
import siteConfig from '@/config/site'
import { useSearchParams } from 'react-router-dom'
import { writeFile, utils } from 'xlsx'

interface IProps {
  changeVisiable: (show: boolean) => void
  selectedRowKeys: Key[]
  changeSelectedRowKeys: (keys: Key[]) => void
  loadData: (page: number) => void
}

const BtnsUser: FC<IProps> = ({
  changeVisiable,
  selectedRowKeys,
  changeSelectedRowKeys,
  loadData
}) => {
  const [show, setShow] = useState(false)
  const [search, setSearch] = useSearchParams()
  let page = search.get('page') ? Number(search.get('page')) : 1
  let query = Object.fromEntries(search.entries())

  const [modal, contextHolder] = Modal.useModal()
  // 批量删除指定的用户
  const batchRemoveUser = () => {
    modal.confirm({
      icon: <ExclamationCircleOutlined />,
      title: '确认删除',
      content: '您真要的删除所选中的用户列表信息吗？',
      okText: '确认删除',
      cancelText: '取消删除',
      onOk: async () => {
        let ret = await batchRemoveUserApi(selectedRowKeys as number[])
        if (siteConfig.pageSize == selectedRowKeys.length) {
          // 全选
          if (page != 1) {
            page--
          }
        }
        loadData(page)
        changeSelectedRowKeys([])
        setSearch({ ...query, page: String(page) })
      }
    })
  }
  // 选中导出excel数据
  const exportUsersExcel = async () => {
    setShow(true)
    let ret = await getUidsToUsersApi(selectedRowKeys as number[])
    // 创建工作薄
    const wb = utils.book_new()
    // 把数据写入到工作薄中的单元表中
    const sheet = utils.json_to_sheet(ret.data)
    utils.book_append_sheet(wb, sheet, '用户列表')
    writeFile(wb, '用户管理.xlsx')
    setShow(false)
    changeSelectedRowKeys([])
  }

  return (
    <>
      {contextHolder}
      {show && (
        <Spin
          fullscreen
          tip={<h3>导出中...</h3>}
          indicator={<LoadingOutlined style={{ fontSize: 50 }} spin />}
        />
      )}
      <div className="btns-user-box">
        <ConfigProvider
          theme={{
            components: {
              Button: {
                defaultBg: '#67c23a',
                defaultHoverBg: '#93c47a',
                defaultHoverBorderColor: '#93c47a',
                defaultColor: '#fff',
                defaultHoverColor: '#fff'
              }
            }
          }}
        >
          <Flex gap="small" wrap="wrap">
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                changeVisiable(true)
              }}
            >
              新增用户
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length > 0 ? false : true}
              onClick={batchRemoveUser}
            >
              批量删除所选用户
            </Button>
            <Button
              icon={<FileExcelOutlined />}
              disabled={selectedRowKeys.length > 0 ? false : true}
              onClick={exportUsersExcel}
            >
              导出所选用户记录
            </Button>
          </Flex>
        </ConfigProvider>
      </div>
    </>
  )
}

export default BtnsUser
